package com.liufei.work;

import com.liufei.dao.DatabaseReader;
import com.liufei.util.DatabaseUtils;
import com.liufei.util.PoiUtils;
import org.apache.poi.hssf.usermodel.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author LiuFei
 * @create 2017-12-25 11:55
 *
 * 参考博客：
 * http://blog.csdn.net/sxdtwym/article/details/54379592
 * http://blog.csdn.net/jiajane/article/details/48176885
 * http://blog.csdn.net/hantiannan/article/details/5312133
 *
 */
public class Main {

    // 此处不用修改，只需修改properties文件就行
    private static final String DATABASE_URL = DatabaseUtils.url;
    private static final String DATABASE_NAME = DATABASE_URL.substring(DATABASE_URL.lastIndexOf("/") + 1, DATABASE_URL.indexOf("?"));
    private static final String[] DETAIL_HEAD_CONTEXT = {"字段中文名", "字段英文名", "类型", "长度", "默认值", "可空", "备注"};
    private static final String[] PROFILE_HEAD_CONTEXT = {"序号", "数据表中文名称", "数据表英文名称", "特殊说明", "是否新创建", "备注"};

    public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {

        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFCellStyle contextCellStyle = PoiUtils.getContextStyle(workbook);
        HSSFCellStyle headCellStyle = PoiUtils.getHeadStyle(workbook);

        DatabaseReader databaseReader = new DatabaseReader();
        List<Map<String, String>> tableList = databaseReader.getTables(DATABASE_NAME);
        HSSFSheet sheet = workbook.createSheet("数据表一览");
        PoiUtils.setProfileTitle(workbook, sheet);
        PoiUtils.setProfileWidth(sheet);
        PoiUtils.setHeadRow(sheet, 2, PROFILE_HEAD_CONTEXT, headCellStyle);
        int currRow = 3;
        int count = 1;
        for (Map<String, String> map : tableList) {
            // 表信息内容添加
            List<Map<String, String>> columnList = databaseReader.getTableInfo(DATABASE_NAME, map.get("TABLE_NAME"));
            HSSFSheet colSheet = workbook.createSheet(map.get("REMARKS"));
                PoiUtils.setDetailTitle(workbook, colSheet, map);
                PoiUtils.setDetailWidth(colSheet);
                PoiUtils.setHeadRow(colSheet, 2, DETAIL_HEAD_CONTEXT, headCellStyle);
                int nowRow = 3;
                PoiUtils.setDetailContext(colSheet, nowRow, columnList, contextCellStyle);

            // 数据库一览表内容添加
            PoiUtils.setProfileContextRow(sheet, currRow++, count++, map, contextCellStyle);

        }

        DatabaseUtils.closeConnection(databaseReader.getConnection());
        PoiUtils.write("F:/" + DATABASE_NAME +"数据库结构定义说明.xls", workbook);
    }
}
